package com.hyy.controller;

import com.hyy.bean.MaskUser;
import com.hyy.service.UserService;
import com.hyy.service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet",urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


		request.setCharacterEncoding( "utf-8" ); //必须写在第一位，因为采用这种方式去读取数据，否则 数据会出错。
		//设置这样方式去读。这样中文就能够读取出来了，但是需要注意。表单的发送方式必须是method='post'
		response.setContentType( "text/html;charset=utf-8" );
		//获取请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String useraccount = request.getParameter("useraccount");

		if ( username.equals("")||password.equals("")||username==null||password==null){
			request.setAttribute("msg","用户名或密码不能为空");
			request.getRequestDispatcher("jsp/register.jsp").forward(request,response);
		}

		MaskUser user = new MaskUser(useraccount,username,password,0);
		UserService userService = new UserServiceImpl();

		if(!userService.register(user)){//用户信息错误，跳转到登录页面
			//需要给出提示信息
			request.setAttribute("msg","账号已存在");
			request.getRequestDispatcher("jsp/register.jsp").forward(request,response);
		}else{//用户信息正确的，跳转到首页页面
			request.getSession().setAttribute("user",user);
			response.sendRedirect("/index.jsp");
		}

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request,response);
	}
}
